/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dnbW.dbW.DataSource;
import dnbW.dbW.DatabaseInfo;
import dnbW.dbW.PathExpression;
import dnbW.dbW.sucxentdbW.SucxentQueryTranslator;
import dnbW.uiW.DNBW;
import dnbW.uiW.dbW.AddDatabaseDialog;
import dnbW.uiW.dbW.AddDatabaseTask;
import dnbW.uiW.dbW.DatabaseController;
import dnbW.uiW.dbW.DiskStorageManager;
import dnbW.uiW.dbW.LoadSchemaTask;
import dnbW.uiW.queryW.modelW.XComparisonNodeObject;
import dnbW.uiW.queryW.visual.IdentityPathSQLTask;
import dnbW.uiW.queryW.visual.MergeProcessor;
import dnbW.uiW.queryW.visual.RetrieveFinalResultsTask;
import dnbW.uiW.queryW.visual.SinglePathEditWizard;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tree.TreeBean;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ibm.db2.jcc.b.i;

/**
 *
 * @author Andree
 */
public class Controller extends HttpServlet {
    
    public static String SUXCENT_SCRIPT_PATH = null;
    
    public static String BULK_PATH = null;
    
    public DatabaseInfo selectedDatabase = null;
    
    public static String selectedDataSource = null;
    
    public static String resultSelectedDataSource = null;
    
    public static List<String> listSelectedDataSources = null;
    
    public static Connection con = null;
    
    private net.minidev.json.JSONArray data;
    
    private TreeBean tb;
    
    private String uploadFileAbsolutePath = null;
    
    public static String draggedElement = null;
    
    private boolean newQuery = false;
    
    public static int totalCount = 0;
    
    public static int valueCount;
    
    public static String enteredValue = null;
    
    public static HashMap<String, DefaultMutableTreeNode> currentSelectedNodes = null;
    
    public static HashMap<String, DefaultMutableTreeNode> initSelectedNodes = null;
    public static DefaultMutableTreeNode initDraggNode=null;
    private int levelCount = 0;
    
    LoadSchemaTask loadSchemaTask = new LoadSchemaTask();
    
    public static String newQueryDraggedNode = null;
    
    public static long newQueryID;
    
    public static String operator;
    
    public static DefaultMutableTreeNode valueDraggedNode = null;
    
    public static DefaultMutableTreeNode finalTree = null;
    public static XComparisonNodeObject initObject=null;
    
    public static PathExpression initialPath = null;
    
    public static PathExpression currentPath = null;
    
    public static int count;
    
    private boolean isAlreadyMergeNotAllowed;
    
    private boolean isSelectedDBNull;
    
    private Map<DatabaseInfo,List> dataSourcesByDB = new HashMap<DatabaseInfo,List>();
    
    public static boolean isNewTab_OR_TabSwitched;
    
    public static int tabNumber = 0;
    
    public static boolean isTabSwitchedForValueTree;
    
    public Map visualTextMap = new HashMap();
    
    public Map candidateDatbases;
    public static PathExpression leftJoinPath = null;
    public static PathExpression rightJoinPath=null;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
               
        String criteria = request.getParameter("criteria");
        
        String root = request.getParameter("root");
        
        SUXCENT_SCRIPT_PATH = getServletContext().getRealPath("script/SUCXENT-Colin.sql");
        
        BULK_PATH = getServletContext().getRealPath("bulk/").concat("\\");
        
        
        if((criteria != null)&&(root == null))
        {       //Block to Add database with datasource if any
                if(criteria.equals("ADDDATABASE"))
                {
                        String host = null;
                        String dbName = null;
                    try {
                            host = request.getParameter("host");
                            dbName = request.getParameter("db");
                            String userName = request.getParameter("user");
                            String password = request.getParameter("pwd");
                            String dataSources = request.getParameter("ds");
                            // check if database already exists
                            String url = "jdbc:sqlserver://" + host + ":1433;databaseName=master";
                            Connection connection = DriverManager.getConnection(
                                    url,
                                    userName,
                                    password);
                            Statement statement = connection.createStatement();
                            String sql =
                                    "select count(*)\n" +
                                    "from sys.databases\n" +
                                    "where name = '" + dbName + "'";
                            ResultSet result = statement.executeQuery(sql);

                            while (result.next()) {
                                int count = result.getInt(1);
                                if (count != 0) {
                                    throw new Exception(
                                            "Database Name: " +
                                            dbName +
                                            " already exists.\n" +
                                            "Please choose a different name.");
                                }
                            }                     

                            DatabaseInfo db = new DatabaseInfo(host, dbName, userName, password);
                            AddDatabaseDialog add = new AddDatabaseDialog();
                            add.setDatabaseInfo(db);

                            DNBW.getDatabaseController().addDatabase(db);

                            if(dataSources != null && !"".equals(dataSources.trim())){
                                String[] list = dataSources.split(";");
                                for(String localDataSource : list)
                                {    
                                    db.addDataSource(localDataSource);
                                    
                                    DataSource dataSource = db.getDataSource(localDataSource);

                                    DefaultMutableTreeNode dataSourceNode = loadSchemaTask.loadSchema(db, dataSource);

                                    DatabaseController.dataSourceNodesList.put(localDataSource, dataSourceNode);
                                }    
                            }

                            selectedDatabase = db;

                            con = selectedDatabase.getDbConnection();

                            listSelectedDataSources = new ArrayList<String>();

                            listSelectedDataSources = selectedDatabase.retrieveDataSources();

                            dataSourcesByDB.put(selectedDatabase, listSelectedDataSources);

                            currentSelectedNodes = new HashMap<String, DefaultMutableTreeNode>();

                            DatabaseController dbController = DNBW.getDatabaseController();

                            String str = selectedDatabase.getDbName()+"@localhost"+"#";

                            for(DatabaseInfo tempdb : dbController.getDatabaseList()){
                                if(!((tempdb.getDbName()).equals(selectedDatabase.getDbName())))
                                    str += tempdb.getDbName()+"@localhost"+"#";
                            }
                            int lasHashIndex = str.lastIndexOf("#");
                            str = str.substring(0, lasHashIndex);

                            response.setContentType("plain/text");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write(str);
                    
                     } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                //Block to set selected database from list of databases
                else if(criteria.equals("SELECTEDATABASE"))
                {
                        isSelectedDBNull = false;    
                    
                        String selectedDB = request.getParameter("database");

                        System.out.println("selectedDB = "+selectedDB);

                        int i = selectedDB.indexOf("@");

                        selectedDB = selectedDB.substring(0, i);

                        selectedDatabase = DiskStorageManager.loadSelectedDatabase(selectedDB);
                        
                        if(selectedDatabase != null)
                        {     
                            listSelectedDataSources = new ArrayList<String>();
                            
                            listSelectedDataSources = selectedDatabase.retrieveDataSources();
                            
                            dataSourcesByDB.put(selectedDatabase, listSelectedDataSources);

                            con = selectedDatabase.getDbConnection();

                            currentSelectedNodes = new HashMap<String, DefaultMutableTreeNode>();

                            levelCount = 0;
                        }
                        else if(selectedDatabase == null)
                        {
                            isSelectedDBNull = true;
                        }
                }
                //TODO:Block to create visual display when value entered
                else if((criteria.equals("JOIN"))){
                	String leftNode=request.getParameter("leftJoinNode");
                	String rightNode=request.getParameter("rightJoinNode");
                	DefaultMutableTreeNode leftJoinNode=(DefaultMutableTreeNode) initSelectedNodes.get(leftNode);
                	DefaultMutableTreeNode rightJoinNode=(DefaultMutableTreeNode) currentSelectedNodes.get(rightNode);
                	leftJoinPath=new PathExpression(leftJoinNode, selectedDatabase);
                	rightJoinPath=new PathExpression(rightJoinNode, selectedDatabase);
                	System.out.println("selected nodes for join:"+leftNode+":"+rightNode);
                	System.out.println("Datesource for join:"+leftJoinPath.getDataSource().getName()+":"+rightJoinPath.getDataSource().getName());
                	
                	
                }
                else if((criteria.equals("SUBMITVALUE"))&&(newQuery == true))
                {
                    try{    
                        enteredValue = request.getParameter("value");

                        operator = request.getParameter("operator");
                        
                        char lastChar = operator.charAt((operator.length())-1);

                        operator = SinglePathEditWizard.setOperator(operator);
                        
                        System.out.println("*********** lastChar = "+ operator+" **************");
                        
                        valueDraggedNode = new DefaultMutableTreeNode();

                        valueDraggedNode = (DefaultMutableTreeNode) currentSelectedNodes.get(draggedElement);
                        
                        currentPath = new PathExpression(valueDraggedNode, selectedDatabase);
                        if(initObject==null){
                        	initObject=new XComparisonNodeObject(valueDraggedNode, currentPath, enteredValue, operator);
                        }
                        IdentityPathSQLTask identityPathSQLTask = new IdentityPathSQLTask();
                        //TODO: Join condition
                        if(currentPath.getDataSource().getName().equals(initialPath.getDataSource().getName())){
                        identityPathSQLTask.identifyPath(valueDraggedNode, selectedDatabase, initialPath, enteredValue, operator);
                        }else{
                          identityPathSQLTask.identifyPath(selectedDatabase,initObject,initDraggNode, valueDraggedNode,initialPath,currentPath,enteredValue, operator, leftJoinPath, rightJoinPath);
                        }
                       
                        
                        String image = null;
                        
                        switch (lastChar)
                        {
                            case '0':
                              image="operator_null";
                              break;
                            case '1':
                              image="operator_equal";
                              break;
                            case '2':
                              image="operator_not_equal";
                              break;
                            case '3':
                              image="operator_greater_than";
                              break;
                            case '4':
                              image="operator_greater_than_equal";
                              break;
                            case '5':
                              image="operator_less_than";
                              break;
                            case '6':
                              image="operator_less_than_equal";
                              break;
                            case '7':
                              image="operator_containing";
                              break;    
                        } 
                        TreeNode tr =  valueDraggedNode.getRoot();
                       // currentPath.getDataSource().getName().equals(initialPath.getDataSource().getName());
                        String dataSource= "Data Source: "+currentPath.getDataSource().getName();
                        String initDataSource="Data Source: "+initialPath.getDataSource().getName();
                        dataSource = dataSource.substring(13, dataSource.length());
                        initDataSource=initDataSource.substring(13, initDataSource.length());
                        System.out.println("Initial Root = "+initDataSource);
                        System.out.println("Current Root="+dataSource);
                        String responseText=null;
                        if(currentPath.getDataSource().getName().equals(initialPath.getDataSource().getName())){
                        	responseText= image +"#"+ dataSource +" : "+ valueDraggedNode.toString(); 
                        }else{
                        	responseText=image +"#"+ dataSource +" : "+ valueDraggedNode.toString(); 
                        }
                        System.out.println("*********** responseText = "+ responseText +" **************");
                        
                        response.setContentType("plain/text");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(responseText);
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    } 

                }
                //Block to select new query
                else if(criteria.equals("NEWQUERY"))
                {                  
                    initialPath = null;
                    IdentityPathSQLTask.nextTableId = 0;
                    RetrieveFinalResultsTask.intersectionTableNames.clear();
                    MergeProcessor.previousPath.clear();
                    isAlreadyMergeNotAllowed = false;
                    ++newQueryID;
                    if(!newQuery)
                        newQuery = true;
                }
                
                //TODO:Dragged Element to get Count for result
                    else if(criteria.equals("DRAGED_ELEMENT_NEW_QUERY"))
                    {
                        try
                        {
                            draggedElement = request.getParameter("dragElement");
                            initSelectedNodes=currentSelectedNodes;
                            DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) currentSelectedNodes.get(draggedElement);
                            initDraggNode=draggedNode;
                            TreeNode tr =  draggedNode.getRoot();
                            
                            String dataSource = (tr.getChildAt(0)).toString();
                            
                            dataSource = dataSource.substring(13, dataSource.length());
                            
                            resultSelectedDataSource = dataSource;
//                            currentPath = new PathExpression(valueDraggedNode, selectedDatabase);
                            initialPath = new PathExpression(draggedNode, selectedDatabase);
                            System.out.println(initialPath.getDataSource().getName());
                            
                            System.out.println(" ******** initialPath ********* = "+initialPath.toString());

                            totalCount = DatabaseController.getIdentityPath(initialPath, con);
                            
                            System.out.println("Count = "+totalCount);
                            
                            newQueryDraggedNode = draggedNode.toString();
                            
                            isNewTab_OR_TabSwitched = false;
                            
                            isTabSwitchedForValueTree = false;
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                        }    
                       
                    }
                    
                    //Opening Dialog Box Depending upon Dragged Element 
                    else if(criteria.equals("DRAGED_ELEMENT_VALUE"))
                    {
                        if(initialPath != null)
                        {    
                            draggedElement = request.getParameter("dragElement");
                            try
                            {
                                  boolean isMergeAllowed = false;
                                
                                  DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) currentSelectedNodes.get(draggedElement);  

                                  currentPath = new PathExpression(draggedNode, selectedDatabase);
                                  
                                  if(currentPath.getDataSource().getName().equals(initialPath.getDataSource().getName()))
                                  {
                                      if(MergeProcessor.previousPath.isEmpty())
                                      {
                                          MergeProcessor.previousPath.add(currentPath);                                      
                                      }
                                      else
                                      {
                                          isMergeAllowed = MergeProcessor.processMergePossible();
                                          
                                          if(!isMergeAllowed)
                                          {    
                                              MergeProcessor.previousPath.clear();
                                              isAlreadyMergeNotAllowed = true;
                                          }
                                          
                                          System.out.println("Is merge allowed = "+isMergeAllowed);                                         
                                      }
                                  }else{
                                	  
                                  }
                                 
                                  String responseText = null;
                                  
                                  if((isMergeAllowed)&&(SucxentQueryTranslator.isPathLeaf(currentPath))&&(!isAlreadyMergeNotAllowed))
                                  {
                                        String previousPath = String.valueOf(MergeProcessor.previousPath.get(0));
                                        
                                        MergeProcessor.previousPath.clear();
                                        
                                        int i = previousPath.lastIndexOf("/");
        
                                        String str2 = previousPath.substring(0, i); 

                                        int i2 = str2.lastIndexOf("/");

                                        String str3 = previousPath.substring(i2+1, str2.length());
                                        
                                        StringBuilder message = new StringBuilder();
                                        message.append("The new condition can refer to the same "
                                                + str3 + " with condition(s):<p>");
                                        
                                        message.append(previousPath + " " +
                                                    operator + " " + enteredValue + "<p>");
                                        
                                        message.append("Do you want to merge them together? <p>");
                                        
                                        message.append("<input type='radio' name='merge' value='mergeYes' checked='true'>Yes, merge them &nbsp;&nbsp;&nbsp;&nbsp;<input type='radio' name='merge' value='mergeNo'>No, don't merge<br>");
                                        
                                        responseText = "OPEN_SEARCH_VALUE_LEAF_FORM#"+ currentPath +"#"+ message.toString();
                                        
                                        System.out.println("******** Final Mergerd Message = "+ responseText);
                                  }       
                                  else if(SucxentQueryTranslator.isPathLeaf(currentPath))
                                  {
                                      responseText = "OPEN_SEARCH_VALUE_LEAF_FORM#"+ currentPath;
                                  } 
                                  else
                                  {
                                      responseText = "OPEN_SEARCH_VALUE_NON_LEAF_FORM#"+ currentPath;
                                  }

                                  response.setContentType("plain/text");
                                  response.setCharacterEncoding("UTF-8");
                                  response.getWriter().write(responseText);

                            }
                            catch(Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            response.setContentType("plain/text");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write("exception");        
                        }
                    }
                //Block to create final value tree(right side of window) 
                else if(criteria.equals("LOAD_FINAL_TREE"))
                {
                    try
                    {
                        String visualText = request.getParameter("visualText");
                        System.out.println(visualText+"*******************************************");
                        
                        visualTextMap.put(tabNumber,visualText);
                        
                        System.out.println("visualTextMap = "+visualTextMap.size());
                        
                        finalTree = new DefaultMutableTreeNode();
                        
                        DefaultMutableTreeNode draggedNode = (DefaultMutableTreeNode) currentSelectedNodes.get(draggedElement);  
                        
                        RetrieveFinalResultsTask retrieveFinalResultsTask = new RetrieveFinalResultsTask(selectedDatabase,initialPath);
                        
                        finalTree = retrieveFinalResultsTask.getFinalResultTree();
                        
                        isTabSwitchedForValueTree = false;
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }    
                }        
                //Block to create list from which selected database is deleted 
                else if(criteria.equals("DELETE_DATABASE_LIST"))
                {   
                    candidateDatbases = new HashMap();
                    
                    DatabaseController dbController = DNBW.getDatabaseController();
                    
                    String str = "";
                    
                    for(DatabaseInfo db : dbController.getDatabaseList()){
                        candidateDatbases.put(db.getDbName(), db);
                    }
                    
                    Iterator it = candidateDatbases.entrySet().iterator();
                    
                    while(it.hasNext())
                    {
                        String tempStr = it.next().toString();
                        int indexOfEqual = tempStr.indexOf("=");
                        tempStr = tempStr.substring(indexOfEqual+1, tempStr.length());
                        str += tempStr+"#";
                    }    
                    
                    int lasHashIndex = str.lastIndexOf("#");
                    str = str.substring(0, lasHashIndex);

                    response.setContentType("plain/text");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(str);
                    
                }  
                //Block to delete selected database
                else if(criteria.equals("DELETE_DB"))
                {
                    try
                    {
                        String selectedDB = request.getParameter("database");

                        System.out.println(selectedDB);
                        
                        int indexOfAt = selectedDB.indexOf("@");
                        
                        selectedDB = selectedDB.substring(0, indexOfAt);

                        DatabaseController dbController = DNBW.getDatabaseController();
                        
                        if(candidateDatbases.containsKey(selectedDB))
                        {
                                dbController.setCurrentDb(null);
                                dbController.deleteDatabase((DatabaseInfo)candidateDatbases.get(selectedDB));
                        }    
                        
                        String str = "";
                    
                        for(DatabaseInfo db : dbController.getDatabaseList()){
                            str += db.getDbName()+"@localhost"+"#";
                        }
                        int lasHashIndex = str.lastIndexOf("#");
                        str = str.substring(0, lasHashIndex);

                        response.setContentType("plain/text");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(str);
                    }
                    catch(Exception e)
                    {
                            e.printStackTrace();
                    }
                    
                }
                //Block to add data source externally in database
                else if(criteria.equals("ADD_DATA_SOURCE"))
                {
                    try
                    {    
                        boolean isDataSourceAlreadyPresent = false;

                        String responseText = "";

                        String dataSources = request.getParameter("dataSourceName");

                        Collection<String> dataSourceList = selectedDatabase.getDataSourceNames();

                        if(dataSources != null && !"".equals(dataSources.trim())){
                            String[] list = dataSources.split(";");
                            for(String dataSource : list)
                               if (dataSourceList.contains(dataSource)) 
                               {
                                    isDataSourceAlreadyPresent = true;
                                    responseText = "exp#Data Source : "+dataSource+" is Already Added";
                                    break;
                               }    
                        }

                        if(isDataSourceAlreadyPresent)
                        {
                            response.setContentType("plain/text");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write(responseText);  
                        }
                        else
                        {
                            if(dataSources != null && !"".equals(dataSources.trim())){
                                String[] list = dataSources.split(";");
                                for(String localDataSource : list)
                                {   
                                    selectedDatabase.addDataSource(localDataSource);
                                    
                                    DataSource dataSource = selectedDatabase.getDataSource(localDataSource);

                                    DefaultMutableTreeNode dataSourceNode = loadSchemaTask.loadSchema(selectedDatabase, dataSource);

                                    DatabaseController.dataSourceNodesList.put(localDataSource, dataSourceNode);
                                }    
                            }
                            
                            listSelectedDataSources = new ArrayList<String>();
                            
                            listSelectedDataSources = selectedDatabase.retrieveDataSources();
                            
                            dataSourcesByDB.put(selectedDatabase, listSelectedDataSources);
                            
                            response.setContentType("plain/text");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write("success");      
                        } 
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }    
                }
                
                else if(criteria.equals("DELETE_DS"))
                {
                    try
                    {
                        String dataSource = request.getParameter("datasource");
                    
                        selectedDatabase.deleteDataSource(dataSource);
                        
                        listSelectedDataSources = new ArrayList<String>();
                            
                        listSelectedDataSources = selectedDatabase.retrieveDataSources();
                        
                        dataSourcesByDB.put(selectedDatabase, listSelectedDataSources);
                    }   
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }    
                }    
                        
                
                else if(criteria.equals("SELECT_DATA_SOURCES"))
                {
                      String responseText = "";
                      Iterator it = dataSourcesByDB.get(selectedDatabase).iterator();
                                   
                      while(it.hasNext())
                      {
                          String DS = (String) it.next();
                          responseText += DS +"#";
                      }
                      
                      int lastIndexOfHash = responseText.lastIndexOf("#");
                      responseText = responseText.substring(0, lastIndexOfHash);
                      
                      response.setContentType("plain/text");
                      response.setCharacterEncoding("UTF-8");
                      response.getWriter().write(responseText);
                } 
                
                else if(criteria.equals("SELECTED_DATA_SOURCE"))
                {        
                    String selectedDS = request.getParameter("selectedDS");
                    
                    selectedDataSource = selectedDS;
                }
                //new query tab
                else if(criteria.equals("NEWTAB_OR_TABSWITCHED"))
                { 
                    tabNumber = Integer.parseInt(request.getParameter("tabNumber"));
                    
                    isNewTab_OR_TabSwitched = true;
                    
                    isTabSwitchedForValueTree = true;
                    
                    response.setContentType("plain/text");
                    response.setCharacterEncoding("UTF-8");
                    
                    if(visualTextMap.containsKey(tabNumber))    
                        response.getWriter().write((String)visualTextMap.get(tabNumber));
                    else    
                        response.getWriter().write("");
                }
                
                else if(criteria.equals("DELETETAB"))
                { 
                    int tab = Integer.parseInt(request.getParameter("tabNumber"));
                    
                    ResultTree.resultTreeMap.remove(tab+"_"+0);
                    ResultTree.resultTreeMap.remove(tab+"_"+1);
                    
                    visualTextMap.remove(tab);
                    
                    ValueTree.valueTreeMap.remove(tab);
                    
                    response.setContentType("plain/text");
                    response.setCharacterEncoding("UTF-8");
                    
                    if(visualTextMap.containsKey(tab))    
                        response.getWriter().write((String)visualTextMap.get(tab));
                    else
                        response.getWriter().write("");
                }
                
        }
        else if(root != null)
        {   
            try{
                    if(isSelectedDBNull)
                    {
                        data = new net.minidev.json.JSONArray();
                                   
                        tb = new TreeBean();
                        tb.setId("No");
			tb.setText(" No Database Selected");
			tb.setClasses("No");
                        tb.setHasChildren(false);
                        tb.setExpanded(false);
                        data.add(tb);
                    }    
                    else
                    {    
                        if(root.equals("source"))
			{       
                                   data = new net.minidev.json.JSONArray();
                                   
                                   Iterator it = dataSourcesByDB.get(selectedDatabase).iterator();
                                   
                                   while(it.hasNext())
                                   {
                                       String DS = (String) it.next();
                                       
                                       DefaultMutableTreeNode rootNode = DatabaseController.dataSourceNodesList.get(DS);
                                       
                                       tb = new TreeBean();
                                       tb.setId(rootNode.toString());
                                       tb.setText(rootNode.toString());
                                       tb.setClasses(rootNode.toString());

                                       if(rootNode.getChildCount()>0)
                                            tb.setHasChildren(true);
                                       else
                                            tb.setHasChildren(false);

                                       tb.setExpanded(false);

                                       data.add(tb);
                                   }
			}
                          else if(root.contains("Data Source"))
      			{
                            data = new net.minidev.json.JSONArray();
                            
                            Iterator it = dataSourcesByDB.get(selectedDatabase).iterator();
                                   
                                   while(it.hasNext())
                                   {
                                       String DS = (String) it.next();
                                       
                                       if(DS.equals(root.substring(13, root.length())))
                                       {
                                            DefaultMutableTreeNode rootNode = DatabaseController.dataSourceNodesList.get(DS);
                               
                                            for (Enumeration e = rootNode.children(); e.hasMoreElements();) {
                                                DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) (e.nextElement());
                                                String idValue = "Level_"+(++levelCount);
                                                currentSelectedNodes.put(idValue, childNode);
                                                tb = new TreeBean();
                                                tb.setId(idValue);
                                                tb.setText(childNode.toString());
                                                tb.setClasses("drg ui-draggable");

                                                if(childNode.getChildCount()>0)
                                                   tb.setHasChildren(true);
                                                else
                                                   tb.setHasChildren(false);

                                                tb.setExpanded(false);

                                                data.add(tb);
                                            } 
                                       }
                                   }
                            
                        }
                        else
                          {
                              data = new net.minidev.json.JSONArray();
                              
                              DefaultMutableTreeNode node = currentSelectedNodes.get(root);
                              
                              for (Enumeration e = node.children(); e.hasMoreElements();) {
                                    DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) (e.nextElement());
                                    String idValue = "Level_"+(++levelCount);
                                    currentSelectedNodes.put(idValue, childNode);
                                    tb = new TreeBean();
                                    tb.setId(idValue);
                                    tb.setText(childNode.toString());
                                    tb.setClasses("drg ui-draggable");
                                    
                                    if(childNode.getChildCount()>0)
                                       tb.setHasChildren(true);
                                    else
                                       tb.setHasChildren(false);

                                    tb.setExpanded(false);

                                    data.add(tb);
                                }
                          }
                    }     
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
            
                response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(data);
            
        }

                
        else if(ServletFileUpload.isMultipartContent(request))
        {
            // Create a factory for disk-based file items 
            FileItemFactory factory = new DiskFileItemFactory(); 
            // Create a new file upload handler 
            ServletFileUpload upload = new ServletFileUpload(factory); 
            try { // Parse the request 
                List /* FileItem */ items = upload.parseRequest(request); 
                Iterator iterator = items.iterator(); 
                    while (iterator.hasNext()) 
                    { 
                        FileItem item = (FileItem) iterator.next(); 
                        if (!item.isFormField()) 
                        { 
                            String fileName = item.getName();	 
                            String rootPath = getServletContext().getRealPath("/"); 
                            File path = new File(rootPath + "/uploads"); 
                            if (!path.exists()) 
                            { 
                                boolean status = path.mkdirs(); 
                            } 
                            File uploadedFile = new File(path + "/" + fileName); 
                            System.out.println(uploadedFile.getAbsolutePath());
                            uploadFileAbsolutePath = uploadedFile.getAbsolutePath();
                            item.write(uploadedFile);

                            //uploadedFile.delete();
                        }
                    }
                    DatabaseController dbController = DNBW.getDatabaseController();
                    
                    File file = new File(uploadFileAbsolutePath);
                    
                    dbController.addDocument(selectedDatabase, file, selectedDataSource);
                            
                    DataSource dataSource = selectedDatabase.getDataSource(selectedDataSource);
                    
                    DefaultMutableTreeNode dataSourceNode = loadSchemaTask.loadSchema(selectedDatabase, dataSource);
                    
                    DatabaseController.dataSourceNodesList.put(selectedDataSource, dataSourceNode);
                    
                    currentSelectedNodes = new HashMap<String, DefaultMutableTreeNode>();
                
                } 
            catch (FileUploadException e) 
            { 
                e.printStackTrace(); 
            } catch (Exception e) 
            { 
                e.printStackTrace(); 
            }           
        }    
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
